package srzy.data

import java.io.File
import srzy.common.Logging
import srzy.common.Common
import srzy.common.Config
import srzy.dao.DBUtil
import scala.collection.mutable.ListBuffer
import srzy.diameter._
import spray.json._
import DefaultJsonProtocol._

object PublicData extends Logging {

  //    var dbCompInfos = Map[String, List[com.dic.ocs.offline.data.DBCompareInfo]]()
  //    if (Config.getValue("root", "config", "DBCompareFlag").toBoolean == true)
  //      dbCompInfos = DBOracle.getCaseInfo
  //  
  //    log.debug("dbCompInfos prepared")
  val DBOracle = DBUtil("CaseInfoSource")

  //  var dbCaseInfos = Map[String, (String, String, String, String, String, String)]()
  val dbCaseInfos = DBOracle.getCaseInfo
  logger.debug("dbCompInfos prepared")

  val prettyPrinter = new xml.PrettyPrinter(800, 2)

  val caseInfos = Common.readFromFile(Config.getValue("root", "config", "CaseNameFile"))
    .filter(x => if (x == "") false else true).map(path => {
      logger.debug("start read file :" + path)
      val f = new File(path)
      if (!f.isFile())
        throw new Exception(path + "并不是一个文件")
      //        throw new Exception("file: " + path + " is not a file")

      val c = new CaseInfo()
      c.casePath = path
      c.caseName = f.getName()
      dbCaseInfos.get(c.caseName) match {
        case Some(dbCaseInfo) => {
          val stdCdr = try {
            dbCaseInfo.stdCdr.asJson.convertTo[List[(String, String)]]
          } catch {
            case ex: org.parboiled.errors.ParsingException => {
              logger.error("Json parser error\n" + dbCaseInfo.stdCdr)
              List.empty[(String, String)]
            }
          }

          c.stdFullCdrs = stdCdr.sortWith((e1, e2) => (e1._1 + e1._2) > (e2._1 + e2._2))
          if (dbCaseInfo.stdRBReceFromSM != "") {
            c.stdReceDCCMsg = dbCaseInfo.stdDCCReceMsg.split("\n-----\n").toList.filter(_ != "")
          }
          c.stdReceFromSMMsg = dbCaseInfo.stdRBReceFromSM.split("\n").toList.filter(_ != "")
          c.stdSendToSMMsg = dbCaseInfo.stdRBSendToSM.split("\n").toList.filter(_ != "")
          //          c.initShell = dbCaseInfo._6
          c.caseDesc = dbCaseInfo.caseDesc
        }
        case None => {
          logger.error("case " + c.caseName + "not define in table SM_AUTO_CASE_INFO")
          //          sys.exit
        }
      }

      val str = Common.readFromFile(path).drop(1).mkString("\n")
      val r1 = """<!--[\u0000-\uffff]*?-->""".r
      val str1 = r1.replaceAllIn(str, "")
      val traffic = (scala.xml.XML.loadString(str1) \\ "traffic").head
      c.sendDCCMsg = (traffic \ "send").toList.flatMap(x => (x \ "command").toList) //.map(x => prettyPrinter.format(x))

      c.sessionId = getSessionId(c.sendDCCMsg.head)

      c.actions = traffic.child.toList.foldLeft(ListBuffer.empty[srzy.module.Action])((l, x) => {
        //        println("label:" + x.label)
        x.label match {
          case "send" =>
            l.append(new srzy.module.SendAction {
              val send = (x \ "command").head
            })
            l
          case "wait-ms" =>
            l.append(new srzy.module.WaitAction {
              val waitTime = Integer.parseInt((x \\ "@value").head.text)
            })
            l
          case "db" =>
            val str = (x \\ "@name").head.text
            l.append(new srzy.module.DbOperAction {
              val source = str
              val dbUtil = DBUtil(str)
              val sqlList = (x \ "sql").toList.map(x => x.text)
            })
            l

          case "cache" =>
            //            val str = (x \\ "@name").head.text
            l.append(new srzy.module.CacheOperAction {
              val sqlList = (x \ "cachesql").toList.map(x => x.text)
            })
            l
          case "CleanCache" =>
            l.append(new srzy.module.CleanCacheAction {})
            l

          case "shell" =>
            l.append(new srzy.module.ShellOperAction {
              val shell = x.text
            })
            l
          case "refreshSM" =>
            l.append(new srzy.module.ShellOperAction {
              val shell = x.text
            })
            l

          case "DCCTimeoutTime" =>
            l.append(new srzy.module.DCCTimeoutAction {
              val time = Integer.parseInt((x \\ "@value").head.text)
            })
            l

          case "receive" =>
            l.append(new srzy.module.ReceAction)
            l

          case "RBSleep" =>
            l.append(new srzy.module.RBMsgSleepAction {})
            l

          case "RBSleepAndDiscard" =>
            l.append(new srzy.module.RBMsgSleepAndDiscardAction {})
            l

          case _ => l
        }
      }).toList

      c
    })
  //    .map(((ci: srzy.data.CaseInfo) => {
  //      for (i <- dbCompInfos if ci.caseName == i._1) {
  //        ci.dbCompareInfo = i._2
  //      }
  //      ci
  //    }))

}